package blockchain

import (
	"crypto/sha256"
	"encoding/hex"
	"strconv"
	"time"
)

type Block struct {
	Timestamp    int64
	Data         string
	PreviousHash string
	Hash         string
}

type Blockchain struct {
	Blocks []*Block
}

func (bc *Blockchain) AddBlock(data string) {
	prevBlock := bc.Blocks[len(bc.Blocks)-1]
	newBlock := createBlock(data, prevBlock.Hash)
	bc.Blocks = append(bc.Blocks, newBlock)
}

func createBlock(data string, prevHash string) *Block {
	block := &Block{
		Timestamp:    time.Now().Unix(),
		Data:         data,
		PreviousHash: prevHash,
		Hash:         "",
	}
	block.Hash = calculateHash(block)
	return block
}

func calculateHash(block *Block) string {
	record := strconv.FormatInt(block.Timestamp, 10) + block.Data + block.PreviousHash
	h := sha256.New()
	h.Write([]byte(record))
	hashed := h.Sum(nil)
	return hex.EncodeToString(hashed)
}

func NewBlockchain() *Blockchain {
	return &Blockchain{[]*Block{createGenesisBlock()}}
}

func createGenesisBlock() *Block {
	return createBlock("Genesis Block", "")
}
